import axios from "axios";
import jsCookie from "js-cookie";
import Qs from "qs"; //引入 qs
import router from "@/router";
import { ElMessage } from "element-plus";
import store from "@/store";

//更改开发地址
let baseURL = "";
let host = "http://192.168.1.188:8080";
if (process.env.NODE_ENV === "development") {
  baseURL = host + "/m.api";
} else {
  baseURL = "http://81.71.14.65:8080/m.api";
}

const instance = axios.create({
  baseURL,
  timeout: 5000, //请求超时
  // headers: { "conten-type": "application/x-www-form-urlencoded" },
});

instance.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么--添加请求头--token
    // config.headers.common["AdminToken"] = sessionStorage.getItem("token");
    config.headers["AdminToken"] = jsCookie.get("token");
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);
// const requestType = ["_mt=edit", "_mt=create", "_mt=delete", "_mt=update"];

// 添加响应拦截器
instance.interceptors.response.use(
  async (res) => {
    // 对响应数据做点什么
    let data = res.data;
    let { errno, errmsg } = data;
    let path = router.currentRoute.value.fullPath;
    if (10006 == errno) {
      //res.data._mt != "Login"
      let formData = {
        ...store.state.AddAdmin.admins,
        _gp: "admin",
        _mt: "login",
      };
      let datas = await post(formData);
      if (200 == datas.data.errno) {
        jsCookie.set("token", datas.data.data);
        return instance.request(res.config);
      }

      console.log(datas, 5656);
      ElMessage.error(errmsg);
      router.replace({ path: "/Login", query: { back: path } }); //登录后返回原来的地方
      return data;
    }

    return res;
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

function get(params) {
  return instance.get("", { params });
}

function post(data, params) {
  return instance.post("", Qs.stringify(data), { params });
}

function upload(url, data) {
  return instance.post(url, data);
}

export { get, post, upload, host };
